<template>
  <div id="app-container">
    <el-container style="height: 100vh;">
      <el-header style="background-color: #409EFF; color: white; text-align: center; line-height: 60px;">
        AI 聊天 式问诊
      </el-header>
      <el-main style="padding: 20px;">
        <el-card class="box-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>对话记录</span>
          </div>
          <div v-for="(message, index) in messages" :key="index" class="text item">
            <div
              :class="{'ai-message': message.sender === 'AI', 'user-message': message.sender === 'User'}"
              class="message-container">
              <div class="message-avatar">
                <el-avatar :src="getAvatarSrc(message.sender)"/>
              </div>
              <el-card class="box-card message-content">
                <!-- 使用 VueMarkdown 来渲染 Markdown 内容 -->
                <VueMarkdown
                  v-if="message.sender === 'AI'"
                  :source="message.text"
                  class="message-text ai-message"
                />
                <VueMarkdown v-if="message.sender === 'User'" :source="message.text" class="message-text user-message"/>
                <el-row>
                  <el-button
                    v-for="(question, index) in formattedGenerateMessage.questions"
                    v-if="message.sender === 'AI'"
                    :key="index"
                    size="small"
                    style="margin-right: 5px; margin-bottom: 5px;"
                    @click="handleQuestionClick(question)"
                  >
                    {{ question }}
                  </el-button>
                </el-row>
              </el-card>
            </div>
          </div>
          <!-- 新增 el-descriptions 组件 -->
          <div v-show="showDetails">
            <el-divider>诊断建议</el-divider>
            <el-descriptions :column="2" class="margin-top" title="AI诊断结果" direction="vertical">
              <el-descriptions-item label="初步诊断建议">{{ formattedMessage.possibleCause }}</el-descriptions-item>
              <el-descriptions-item label="健康建议">{{ formattedMessage.suggestedTests }}</el-descriptions-item>
              <el-descriptions-item label="推荐项目">{{ formattedMessage.suggestedProject }}</el-descriptions-item>
              <el-descriptions-item :span="2" label="挂号科室">{{ formattedMessage.department }}</el-descriptions-item>
              <el-descriptions-item label="挂号推荐程度">
                <el-rate
                  v-model="formattedMessage.level"
                  :texts="recommendationTexts"
                  show-text
                  disabled
                />
                <span style="margin-left: 10px;">{{ getRecommendation(formattedMessage.level) }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div v-show="showDetails">
            <el-descriptions :column="4" class="margin-top" title="" direction="vertical" style="white-space:pre-wrap;">
              <el-descriptions-item label="药物推荐">{{ formattedMessage.recommendedDrug }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        <el-form label-position="top" @submit.native.prevent="sendMessage">
          <el-form-item label="您的问题或症状">
            <el-input v-model="userMessage" type="textarea" autosize placeholder="请输入您的问题或症状"/>
          </el-form-item>
          <el-form-item>
            <!-- 注意这里的 :loading 绑定到 isLoading -->
            <el-button :loading="isLoading" type="primary" native-type="submit">发送</el-button>
            <el-button :loading="isDiagnosisLoading" type="primary" @click="getDiagnosis">获取诊断结果</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import ai from '@/api/ai'
import VueMarkdown from 'vue-markdown'

export default {
  components: { VueMarkdown },
  data() {
    return {
      userMessage: '',
      messages: [
        {
          sender: 'AI',
          text: `您好！我是您的健康助手，很高兴能为您服务。<br><br>` +
            `为了给您提供最恰当的帮助，请尽可能详细地告诉我您遇到了什么症状或问题。比如：<br>` +
            `- 症状首次出现的时间<br>` +
            `- 是否有规律性或特定的触发因素<br>` +
            `- 是否伴随其他不适感<br><br>` +
            `任何细节都将有助于我们进行更准确的分析。如果您不确定从哪里开始，请随时告诉我，我们会一步步来。`
        }
      ],
      showDetails: false, // 控制是否显示详细的AI诊断结果
      formattedMessage: {}, // 存储格式化后的AI响应信息
      formattedGenerateMessage: {}, // 存储格式化后的AI响应信息
      isLoading: false, // 添加这个属性来跟踪发送按钮的加载状态\
      recommendations: {
        1: '观察等待 - 病情轻微，不需要立即就医。',
        2: '预约门诊 - 病情较为轻微，建议尽快预约普通门诊。',
        3: '优先就诊 - 病情可能较为复杂，建议尽早安排时间就诊。',
        4: '尽快就医 - 病情较急，可能存在潜在风险，应尽快前往医院。',
        5: '立即急诊 - 病情危急，需要立即医疗救助。'
      },
      recommendationTexts: [
        '观察等待', '预约门诊', '优先就诊', '尽快就医', '立即急诊'
      ],
      isDiagnosisLoading: false // 获取诊断结果按钮的加载状态
    }
  },
  methods: {
    sendMessage() {
      if (this.userMessage.trim()) {
        // 收集用户之前的提问
        const userPreviousQuestions = this.messages
          .filter(message => message.sender === 'User')
          .map(message => message.text)

        // 如果有诊断建议的问题也一并带上
        const diagnosticQuestions = this.formattedGenerateMessage.questions || []

        // 准备要发送的数据
        const dataToSend = {
          currentQuestion: this.userMessage,
          previousQuestions: userPreviousQuestions,
          diagnosticQuestions: diagnosticQuestions
        }
        this.isLoading = true // 在发送请求前设置为 true
        this.showDetails = false
        // 更新消息列表
        this.messages.push({ sender: 'User', text: this.userMessage })

        // 发送 POST 请求到后端
        ai.generateChat(dataToSend)
          .then(response => {
            const aiResponse = response.data
            // 格式化AI响应信息
            this.formattedGenerateMessage = {
              content: aiResponse.content,
              questions: aiResponse.questions || [] // 确保有 questions 字段

            }
            // 更新消息列表并显示详细信息
            this.messages.push({
              sender: 'AI',
              text: `${aiResponse.content}`
            })
            // this.showDetails = true // 显示详细的AI诊断结果
          })
          .catch(error => {
            console.error('Error fetching AI response:', error)
          })
          .finally(() => {
            this.userMessage = '' // 清空输入框
            this.isLoading = false // 请求完成后设置为 false
          })
      }
    },
    handleQuestionClick(question) {
      // 收集用户之前的提问
      const userPreviousQuestions = this.messages
        .filter(message => message.sender === 'User')
        .map(message => message.text)

      // 准备要发送的数据
      const dataToSend = {
        currentQuestion: question,
        previousQuestions: userPreviousQuestions,
        diagnosticQuestions: [question] // 只包含点击的问题
      }

      this.isLoading = true
      this.showDetails = false
      // 发送 POST 请求到后端
      ai.generateChat(dataToSend)
        .then(response => {
          const aiResponse = response.data
          // 更新消息列表
          this.messages.push({ sender: 'User', text: question })

          // 格式化AI响应信息
          this.formattedGenerateMessage = {
            content: aiResponse.content,
            questions: aiResponse.questions || [] // 确保有 questions 字段
          }

          // 更新消息列表并显示详细信息
          this.messages.push({
            sender: 'AI',
            text: `${aiResponse.content}`
          })
          // this.showDetails = true // 显示详细的AI诊断结果
        })
        .catch(error => {
          console.error('Error sending question:', error)
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    getAvatarSrc(sender) {
      if (sender === 'AI') {
        return 'src/icons/images/AI-04.svg' // 替换为实际的 AI 头像路径
      } else if (sender === 'User') {
        return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' // 替换为实际的用户头像路径
      }
      return '' // 默认头像路径
    },
    getRecommendation(level) {
      if (level === null || level === undefined || !this.recommendations[level]) {
        return '暂无推荐' // 如果没有选择评分，则不显示任何推荐信息
      }
      return this.recommendations[level]
    },
    getDiagnosis() {
      this.isDiagnosisLoading = true // 在发送请求前设置为 true
      // 收集用户之前的提问
      const userPreviousQuestions = this.messages
        .filter(message => message.sender === 'User')
        .map(message => message.text)
      // 如果有诊断建议的问题也一并带上
      const diagnosticQuestions = this.formattedGenerateMessage.questions || []
      // 准备要发送的数据
      const dataToSend = {
        currentQuestion: '获取诊断结果',
        previousQuestions: userPreviousQuestions,
        diagnosticQuestions: userPreviousQuestions
      }
      // 发送 POST 请求到后端
      ai.aiChat(dataToSend)
        .then(response => {
          const aiResponse = response.data
          // 格式化AI响应信息
          // 格式化AI响应信息
          this.formattedMessage = {
            possibleCause: aiResponse.possibleCause,
            suggestedTests: aiResponse.suggestedTests,
            department: aiResponse.department,
            suggestedProject: aiResponse.suggestedProject,
            recommendedDrug: aiResponse.recommendedDrug,
            level: aiResponse.level
          }
          console.log(this.formattedMessage.recommendedDrug)
          this.showDetails = true // 显示详细的AI诊断结果
        })
        .catch(error => {
          console.error('Error fetching AI response:', error)
        })
        .finally(() => {
          this.userMessage = '' // 清空输入框
          this.isDiagnosisLoading = false // 请求完成后设置为 false
        })
    }
  }
}
</script>
<style scoped>
.message-container {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.ai-message {
  flex-direction: row;
  justify-content: flex-start;
}

.user-message {
  flex-direction: row-reverse;
  justify-content: flex-end;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px; /* 调整头像与消息内容的间距 */
}

.user-message .message-avatar {
  margin-right: 0;
  margin-left: 10px; /* 调整用户消息中的头像位置 */
}

.box-card.message-content {
  background-color: #f0f9ff;
  border-radius: 5px;
  padding: 10px;
  max-width: 80%; /* 控制消息框的最大宽度 */
}

.ai-message .message-content {
  background-color: whitesmoke;
  text-align: left;
}

.user-message .message-content {
  background-color: #e0dfff;
  text-align: right;
  padding: 1px; /* 减小用户消息框的内边距 */
}

.message-text {
  word-break: break-word;
}

.user-message .message-content {
  margin-left: auto; /* 确保用户消息靠到最右边 */
}

</style>
